package mall.repository;

import mall.entity.User;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Deprecated
public class UserDao extends BaseDao {

    public List<User> selectList() {
        return executeQuery("select * from  user");
    }

    public List<User> selectList(User user) {
        StringBuilder sb = new StringBuilder("select * from  user where 1=1 ");
        List<Object> params = new ArrayList<>();

        if (user.getId() != null) {
            sb.append(" and id = ?");
            params.add(user.getId());
        }

        if (user.getName() != null) {
            sb.append(" and name like ?");
            params.add("%" + user.getName() + "%");
        }

        return executeQuery(sb.toString(), params.toArray());
    }


    public int insert(User user) {
        String sql = "insert into user(name, username, password, role) values(?, ?, ?, ?)";
        return executeUpdate(sql, user.getName(), user.getUsername(), user.getPassword(), user.getRole());
    }

    public int update(User user) {
        String sql = "update   user set name = ?, username = ?, password = ?,phone = ?, address = ? where id = ?";
        return executeUpdate(sql, user.getName(), user.getUsername(), user.getPassword(), user.getPhone(),user.getAddress(),user.getId());
    }

    public int deleteById(int id) {
        String sql = "delete from   user where id = ?";
        return executeUpdate(sql, id);
    }


    public User selectById(int id) {
        String sql = "select * from   user where id = ?";
        List<User> list = executeQuery(sql, id);
        return list.isEmpty() ? null : list.get(0);
    }


    @Override
    public Object rowToObject(ResultSet rs) throws Exception {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setName(rs.getString("name"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setAddress(rs.getString("address"));
        user.setPhone(rs.getString("phone"));
        user.setRole(rs.getInt("role"));
        return user;
    }

    public User selectByUsernamePassword(String username, String password)  {
        String sql = "select * from   user where username = ? and password = ?";
        List<User> list = executeQuery(sql, username, password);
        return list == null || list.isEmpty() ? null : list.get(0);
    }

    public User selectByUsername(String username)  {
        String sql = "select * from   user where username = ?";
        List<User> list = executeQuery(sql, username);
        return list == null || list.isEmpty() ? null : list.get(0);
    }
}
